package bamin.com.bamindaijia.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.administrator.shane_library.shane.widget.TwoBtnDialog;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.Order;
import bamin.com.bamindaijia.model.Sms;
import cz.msebera.android.httpclient.Header;

public class ComplaintActivity extends ZjbBaseActivity implements View.OnClickListener {

    private ImageView mImg_order_driverImage;
    private TextView mTextView_driverName;
    private TextView mTextView_driveYear;
    private TextView mTextView_orderNum;
    private EditText mEdt_complaint;
    private TextView mTv_editNum;
    private Button mBtn_sure;
    //    private DriverInfo.DatasBean mDriverDatas;
    private Order mOrder;
    private SimpleRatingBar mRatingbar_pingfeng;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaint);
        init();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        mTextView_driverName.setText("司机：" + mOrder.getDriverName());
        mTextView_driveYear.setText("驾龄：" + mOrder.getDriverDrivingTime());
        mTextView_orderNum.setText("接单数：" + mOrder.getDriverOrderSum() + "单");
        if (null != mOrder.getDriverScore()) {
            double driverScore = mOrder.getDriverScore();
            mRatingbar_pingfeng.setRating((float) driverScore);
        }


        String mImage = mOrder.getDriverImage();
        Log.e("checkLogin", "图片URL" + mImage);
        if (mImage != null && !TextUtils.isEmpty(mImage)) {
            ImageLoader.getInstance().clearDiskCache();
            UILUtils.displayImageNoAnim(mImage, mImg_order_driverImage);
        }
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.rela_phone).setOnClickListener(this);
        findViewById(R.id.imageView_back).setOnClickListener(this);
        mBtn_sure.setOnClickListener(this);
        mEdt_complaint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                mTv_editNum.setText("" + s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
//        mDriverDatas = (DriverInfo.DatasBean) intent.getSerializableExtra(Constant.INTENT_KEY.DRIVER_INFO);
        mOrder = (Order) intent.getSerializableExtra(Constant.INTENT_KEY.ORDER);
        Log.e("ComplaintActivity", "initIntent: --->>" + mOrder.getId());
    }

    @Override
    protected void findID() {
        mImg_order_driverImage = (ImageView) findViewById(R.id.img_order_driverImage);
        mTextView_driverName = (TextView) findViewById(R.id.textView_driverName);
        mTextView_driveYear = (TextView) findViewById(R.id.textView_driveYear);
        mTextView_orderNum = (TextView) findViewById(R.id.textView_orderNum);
        mEdt_complaint = (EditText) findViewById(R.id.edt_complaint);
        mTv_editNum = (TextView) findViewById(R.id.tv_edittextNum);
        mBtn_sure = (Button) findViewById(R.id.button_sure);
        mRatingbar_pingfeng = (SimpleRatingBar) findViewById(R.id.ratingbar_pingfeng_driver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;


            case R.id.rela_phone://手机
                dialKeFu();
                break;

            case R.id.button_sure:
                final TwoBtnDialog twoBtnDialog = new TwoBtnDialog(this, "确定是否提交投诉", "确定", "取消");
                twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        if (!TextUtils.isEmpty(mEdt_complaint.getText().toString().trim())) {
                            pushComplaint();

                        } else {
                            Toast.makeText(ComplaintActivity.this, "投诉信息不能为空", Toast.LENGTH_SHORT).show();
                        }

                        twoBtnDialog.dismiss();
                    }

                    @Override
                    public void doCancel() {
                        twoBtnDialog.dismiss();
                    }
                });
                twoBtnDialog.show();
                break;
        }
    }

    /**
     * 投诉成功
     */
    private void pushComplaint() {
        String url = Constant.Url.ADD_COMPLAIN;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("orderId", mOrder.getId());
        params.put("customerId", mOrder.getCustomerId());
        params.put("customerPhone", mOrder.getCustomerPhone());
        params.put("driverId", mOrder.getDriverId());
        params.put("driverPhone", mOrder.getDriverPhone());
        params.put("complainContent", mEdt_complaint.getText().toString().trim());
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("ComplaintActivity", "投诉成功: --->>" + s);

                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if (sms.getStatus() == 0) {
                        showDialog(sms.getMes());
                    } else {
                        showDialog(sms.getMes());
                    }
                } catch (Exception e) {
                    Toast.makeText(ComplaintActivity.this, "数据解析错误", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(ComplaintActivity.this, "数据下载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showDialog(String mes) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(ComplaintActivity.this, mes, "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                finishTo();

            }
        });
        singleBtnDialog.show();
    }

    /**
     * 拨打客服电话
     */
    private void dialKeFu() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},
                    Constant.PERMISSION.CALL_PHONE);
        } else {
            final TwoBtnDialog twoBtnDialog = new TwoBtnDialog(this, "是否直接拨打客服电话400-0593-330", "是", "否");
            twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    twoBtnDialog.dismiss();
                    //用intent启动拨打电话
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000593330"));
                    startActivityTo(intent);
                }

                @Override
                public void doCancel() {
                    twoBtnDialog.dismiss();

                }
            });
            twoBtnDialog.show();
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Complaint Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient.connect();
        AppIndex.AppIndexApi.start(mClient, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(mClient, getIndexApiAction());
        mClient.disconnect();
    }
}
